package me.xhy.java.springboot3.webflux.s02springbootwebflux;

import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;

@RestController
public class S02ControllerAndSSE {

  // Mono 返回单个数据
  @GetMapping("/1")
  public Mono<String> echo1(@RequestParam(value="content", required = false, defaultValue = "hello Mono") String content) {
    return Mono.just(content);
  }

  // Flux 返回多个数据
  @GetMapping("/2")
  public Flux<String> echo2(@RequestParam(value="content", required = false, defaultValue = "hello Flux") String content) {
    return Flux.fromArray(content.split(""));
  }

  // produces = MediaType.TEXT_EVENT_STREAM_VALUE 明确告诉浏览器，本次请求将返回一个 event stream
  // 前台浏览器，网络试图，将有event stream选项卡
  @GetMapping(value = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
  public Flux<String> delay() {
    return Flux.range(1, 10)
        .delayElements(Duration.ofSeconds(1))
        .map(i -> "delay " + i + "<br/>");
  }

  @GetMapping("sse2")
  public Flux<ServerSentEvent<String>> sse2() {
    return Flux.range(1,10)
        .map(i -> ServerSentEvent.builder("sse" + i)
            .id("sse id" + i)
            .comment("sse comment" + i)
            .event("event" + i)
            .build())
        .delayElements(Duration.ofSeconds(1));
  }


}
